package com.git.contractmanagement.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.git.contractmanagement.common.Result;
import com.git.contractmanagement.config.ZfbConfig;
import com.git.contractmanagement.entity.PayOrder;
import com.git.contractmanagement.service.PayOrderService;
import com.git.contractmanagement.service.ZfbPayService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ZfbPayServiceImpl implements ZfbPayService {
    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private ZfbConfig zfbConfig;
    @Autowired
    private PayOrderService payOrderService;

    @Override
    public Boolean verifySign(HttpServletRequest request) {
        //获取请求参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, String> params = new HashMap<>();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String key = entry.getKey();
            String[] values = entry.getValue();
            if (values != null && values.length > 0) {
                params.put(key, values[0]);
            }
        }
        try {
            return AlipaySignature.rsaCheckV1(params, zfbConfig.getAlipayPublicKey(), "UTF-8", "RSA2");
        } catch (AlipayApiException e) {
            System.err.println("支付宝验签异常: " + e.getMessage());
            return false;
        }
    }


    /**
     * 生成支付宝支付表单 HTML
     */

    public String createPayForm(PayOrder payOrder) {
        System.out.printf("我到zfbpayserviceimpl了");
        try {
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setNotifyUrl(zfbConfig.getNotifyUrl());
            request.setReturnUrl("http://localhost:8080/orders");
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            model.setOutTradeNo(payOrder.getOrderNo());
            BigDecimal amount = payOrder.getAmount();
            if (amount == null) {
                amount = new BigDecimal("0.01"); // 沙箱测试金额
            }
            model.setTotalAmount(amount.setScale(2, RoundingMode.HALF_UP).toPlainString());
            // 沙箱测试金额
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            model.setSubject("合同支付订单");
            model.setPassbackParams(URLEncoder.encode("userId=" + payOrder.getUserId(), StandardCharsets.UTF_8));
            request.setBizModel(model);

            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            System.out.println("了");

            if (response.isSuccess()) {
                return response.getBody(); // 返回 HTML 表单
            } else {
                throw new RuntimeException("调用支付宝支付失败: " + response.getMsg());
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException("生成支付宝支付表单异常", e);
        }
    }

    @Override
    public Result refund(PayOrder order, String reason) throws AlipayApiException {
    /*
    退款服务层
    */
        // 1. 构造退款请求
        System.out.println("3333333333333333333333");
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        System.out.println("44444444444444444444444444");
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        System.out.printf("555555555555555555555555");
        model.setOutTradeNo(order.getOrderNo()); // 订单号
        model.setRefundAmount(String.valueOf(order.getAmount())); // 退款金额
        model.setRefundReason(reason); // 退款原因
        request.setBizModel(model);
        System.out.println("order = " + order + ", reason = " + reason);
        System.out.printf("666666666666666666666666666666666666666");
        // 2. 调用支付宝退款接口
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        System.out.printf("7777777777777777777777777777777777");
        // 3. 判断退款结果
        if ("10000".equals(response.getCode())) {
            System.out.printf("888888888888888888888888888888");
            System.out.println("退款成功");
            //TODO,返回退款成功的信息
            // 4. 更新数据库订单状态
            order.setStatus("REFUNDED");  // 标记退款成功
            order.setCreateTime(new Date()); // 可选：记录退款时间
            order.setReason(reason);
            payOrderService.updateById(order); // 保存到数据库
            System.out.println("更新数据订单成功");

            return Result.success("退款成功");
        } else {
            System.out.println("退款失败: " + response.getSubMsg());
            return Result.error("退款失败: " + response.getSubMsg());

        }
    }
}

